package pers.corvey.studyjava.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import pers.corvey.studyjava.exception.BadRequestException;
import pers.corvey.studyjava.model.CourseCategory;
import pers.corvey.studyjava.service.CourseCategoryService;

@Controller
@RequestMapping("/courseCategorys")
public class CourseCategoryController {

    @Autowired
    private CourseCategoryService courseCategoryService;
    
    @GetMapping(headers="Accept=text/html")
    public String show() {
        return "forward://html/showCourseCategory.html";
    }
    
    @GetMapping
    @ResponseBody
    public Iterable<CourseCategory> getCourseCategorys() {
        return courseCategoryService.getCourseCategorys();
    }
    
    @GetMapping("/{courseCategoryId}")
    @ResponseBody
    public CourseCategory getCourseCategoryById(@PathVariable String courseCategoryId) {
        return courseCategoryService.getCourseCategoryById(courseCategoryId);
    }
    
    @PutMapping("/{courseCategoryId}")
    @ResponseBody
    public CourseCategory updateCourseCategory(@PathVariable String courseCategoryId, String name) {
        if (!courseCategoryService.isCourseCategoryExists(courseCategoryId)) {
            throw new BadRequestException("操作失败，不存在相关记录！");
        }
        CourseCategory courseCategory = new CourseCategory();
        courseCategory.setId(courseCategoryId);
        courseCategory.setName(name);
        return courseCategoryService.updateCourseCategory(courseCategory);
    }
    
}
